package net.keebook.webapp.bean;

import java.util.Locale;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import net.keebook.webapp.dao.KeeBookDao;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.model.SessionModel;

import org.apache.log4j.Logger;

@Stateless
public class LoginSupportBean {
	@EJB
	private KeeBookDao keeBookDao;
	
	public void login(User user, SessionModel sessionModel) {
		Logger.getLogger(this.getClass()).info("User " + user.getId() + " logged in successfully");
		
		sessionModel.clear();
		sessionModel.setUserId(user.getId());
		sessionModel.setAdmin(user.getAdmin());
		
		// Restore locale
		if (user.getLanguage() != null && user.getCountry() != null) {
			Locale locale = new Locale(user.getLanguage(), user.getCountry());
			sessionModel.setLocale(locale);
		}
		
		sessionModel.setRequireProfileCompletion(userNeedsProfileCompletion(user));
	}
	
	public String getRedirectionUrl(SessionModel sessionModel) {
		if (!sessionModel.getLoggedIn()) {
			return "login.xhtml";
		}
		if (sessionModel.getRequireProfileCompletion()) {
			return "completeprofile.xhtml";
		}
		if (!sessionModel.getKeeBookSelected()) {
			if (getKeeBookDao().getList(sessionModel.getUserId()).isEmpty()) {
				return "createkeebook.xhtml";
			}
			return "selectkeebook.xhtml";
		}
		return "index.xhtml";
	}
	
	private boolean userNeedsProfileCompletion(User user) {
		if (user.getTermsAccepted() == null || !user.getTermsAccepted()) return true;
		if (user.getName() == null || "".equals(user.getName().trim())) return true;
		if (user.getEmail() == null || "".equals(user.getEmail().trim())) return true;
		return false;
	}

	public KeeBookDao getKeeBookDao() {
		return keeBookDao;
	}

	public void setKeeBookDao(KeeBookDao keeBookDao) {
		this.keeBookDao = keeBookDao;
	}
}
